function ImgAudioClick() {
    document.getElementById("audioBody").play();
}
function InitialClick() {
    document.getElementById("InitialButton").style.display = "none";
    document.getElementById("InitialButton1").style.display = "block";
    document.getElementById("InitialButton2").style.display = "block";
    document.getElementById("InitialButton4").style.display = "block";
    document.getElementById("InitialButton6").style.display = "block";
}
function ShowInitialClick() {
    document.getElementById("InitialButton").style.display = "block";
    document.getElementById("InitialButton1").style.display = "none";
    document.getElementById("InitialButton2").style.display = "none";
    document.getElementById("InitialButton4").style.display = "none";
    document.getElementById("InitialButton6").style.display = "none";
}
function ResetClick() {
    history.go(0);
}
//返回首页
function close_win() {
    document.querySelectorAll("audio").forEach((audio) => audio.pause());
    currentTimestamp = Date.now();
    operationName = "end";
    additionalInfo = "out";
    CommonNetWork();
    api.openWin({
        name: "BasicExpressionNamingSelect",
        url: "./BasicExpressionNamingSelect.html",
        pageParam: {
            uid: userid,
            token: token,
        },
        reload: true,
    });
}
function audioExpressionClick() {
    document.getElementById("audioExpression").style.display = "none";
    document.getElementById("audioExpression").play();
}

//利用http来进行传输麦克风，先是请求麦克风权限
async function getMediaStream() {
    const hasMicrophonePermission = hasPermissionObj("microphone");
    if (!hasMicrophonePermission || !hasMicrophonePermission[0] || !hasMicrophonePermission[0].granted) {
        api.confirm(
            {
                title: "提醒",
                msg: "没有获得 " + "麦克风" + " 权限\n是否前往设置？",
                buttons: ["去设置", "取消"],
            },
            function (ret, err) {
                if (1 == ret.buttonIndex) {
                    reqPermission("microphone");
                    history.go(0);
                }
            }
        );
        return false;
    } else {
    try {
        // 检查是否支持 getUserMedia
        if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
            throw new Error('getUserMedia is not supported in this browser.');
        }

        // 请求麦克风权限
        const videoStream = await navigator.mediaDevices.getUserMedia({
            audio: true, // 请求麦克风
            video: false // 不请求摄像头
        });

        // 检查是否成功获取到流
        if (videoStream) {
            mediaRecorder = new MediaRecorder(videoStream);
            return videoStream;
        } else {
            throw new Error('无法获取音频流。');
        }
    } catch (error) {
        console.error('获取麦克风权限失败：', error);
        throw error;
    }
}
}
document.addEventListener('DOMContentLoaded', () => {
document.getElementById("StartRecord").addEventListener("click", async () => {
    videoStream = await getMediaStream();
    if (videoStream) {
        mediaRecorder.start();
        mediaRecorder.ondataavailable = (event) => {
            if (event.data.size > 0) {
                chunks.push(event.data);
            }
        };
        currentTimestamp = Date.now();
        operationName = "ing";
        additionalInfo = "audio";
        CommonNetWork();
    }
    document.getElementById("StartRecord").style.display = "none";
    document.getElementById("PlayRecord").style.display = "none";
    document.getElementById("StopRecord").style.display = "inline-block";
})
document.getElementById("StopRecord").addEventListener("click", () => {
    if (videoStream) {
        const tracks = videoStream.getTracks();
        // 遍历并停止每一个音频
        tracks.forEach((track) => {
            track.stop();
        });
        mediaRecorder.stop();
        mediaRecorder.onstop = () => {
            blob = new Blob(chunks, { type: "audio/webm" });
            // 上传数据
            uploadVideo(blob);
            chunks = [];
        };
        document.getElementById("StartRecord").style.display = "none";
        document.getElementById("PlayRecord").style.display = "inline-block";
        document.getElementById("StopRecord").style.display = "none";
    }
})

document.getElementById("PlayRecord").addEventListener("click", () => {
    if (blob) {
                const audio = document.getElementById("playAudio");
                audio.src = URL.createObjectURL(blob);
                audio.play();
            } else {
                console.error('No audio blob available to play.');
            }
});

})
function uploadVideo(blob) {
    const blobChunk = blob;
    var chunkSize = 1024 * 1024;
    let start = 0; // 从0开始切片
    let count = 0; //从1开始
    var totalPieces = Math.ceil(blobChunk.size / chunkSize); //总数

    while (start < blobChunk.size) {
        var end = start + chunkSize;
        if (end > blobChunk.size)  {
            //小于1M也传
            end = blobChunk.size;
        }
        uploadChunk(blobChunk.slice(start, end), count, totalPieces, end == blobChunk.size);
        start += chunkSize;
        count++;
    }
}
function uploadChunk(chunk, count, totalPieces, bLast) {
    ImitatefileName =
        userid +
        "—" +
        scene +
        "—" +
        sceneLevel +
        "—" +
        courseType +
        "—" +
        classType +
        "—" +
        classSort +
        "—" +
        groupId +
        "—" +
        currentTimestamp +
        ".mp3";
    var formData = new FormData();
    formData.append("audioFile", chunk);
    formData.append("sliceNumber", count);
    formData.append("totalSlices", totalPieces);
    formData.append("fileName", ImitatefileName);
    formData.append("userid", userid);
    // 使用原生的fetch API示例（可替换为XMLHttpRequest等方式）
    fetch(CommonUrl + "/audio/uploadSlice", {
        method: "post",
        headers: {
            Authorization: `Bearer ${token}`,
        },
        body: formData,
    })
        .then((res) => {
            // 上传成功后的处理
            if (bLast) {
                alert("上传成功");
                // alert(JSON.stringify(res));
            }
        })
        .catch((res) => {
            // 上传失败后的处理
            alert("上传失败");
            // alert(JSON.stringify(res));
        });
}


function reqPermission(one_per, callback) {
    var perms = new Array();
    if (one_per) {
        perms.push(one_per);
    } else {
        perms = ["library", "camera"];
    }
    api.requestPermission(
        {
            list: perms,
            code: 100001,
        },
        function (ret, err) {
            if (callback) {
                callback(ret);
                return;
            }
            var str = "请求结果：\n";
            str += "请求码: " + ret.code + "\n";
            str += '是否勾选"不再询问"按钮: ' + (ret.never ? "是" : "否") + "\n";
            str += "请求结果: \n";
            var list = ret.list;
            for (var i in list) {
                str += list[i].name + "=" + list[i].granted + "\n";
            }
            console.log(JSON.stringify(ret));
        }
    );
}
